const HOST = require('../../../config.js').host
let app = getApp()

Page({
    data:{
        provincesIndex: undefined,
        citiesIndex: undefined,
        areaIndex: undefined,

        form: {
            linkman: '',
            linkmanPhone: '',
            address: '',
            code: '',
            province: '',
            city: '',
            area: '',
            isDefault: 0
        },

        dict: {
            linkman: '收货人',
            linkmanPhone: '电话号码',
            address: '详细地址',
            code: '邮编',
            province: '省份',
            city: '城市',
            area: '地区' 
        }
    },

    save (e) {
        this.saveAddress()
    }, 

    setDefault (e) {
        this.setData({
            'form.isDefault': e.detail.value || this.data.isInit ? 1 : 0
        })
    },

    inputName (e) {
        this.setData({
            'form.linkman': e.detail.value
        })
    },

    inputPhone (e) {
        this.setData({
            'form.linkmanPhone': e.detail.value
        })
    },

    inputDetail (e) {
        this.setData({
            'form.address': e.detail.value
        })
    },

    inputPost (e) {
        this.setData({
            'form.code': e.detail.value
        })
    },

    pickProvince (e) {
        this.setData({
            provincesIndex: e.detail.value,
            'form.province': this.data.provinces[e.detail.value].value,
            citiesIndex: undefined,
            cities: [],
            areaIndex: undefined,
            area: []
        })
        this.getDict(this.data.provinces[e.detail.value].value, 'city')
    },

    pickCity (e) {
        this.setData({
            citiesIndex: e.detail.value,
            'form.city': this.data.cities[e.detail.value].value,
            areaIndex: undefined,
            area: []            
        })
        this.getDict(this.data.cities[e.detail.value].value, 'area')
    },

    pickArea (e) {
        this.setData({
            areaIndex: e.detail.value,
            'form.area': this.data.area[e.detail.value].value            
        })
    },

    /**
     * 获取数据
     */
    getDict (id, type) {
        const param = `${id}/${type}`

        wx.request({
          url: HOST + 'v1/dictionary/getListByType/' + param,
          method: 'GET',
          success: function (res) {
            if (res.data.sysCode === 1) {
                switch (type) {
                    case 'province':
                        this.setData({
                            provinces: res.data.data
                        })
                        break
                    case 'city':
                        this.setData({
                            cities: res.data.data
                        })
                        break
                    case 'area':
                        this.setData({
                            area: res.data.data
                        })
                        break
                    default:
                        break
                }

            }
          }.bind(this)
        })
    },

    getDictChain (id, type) {
        const param = `${id}/${type}`
        const form = this.data.form
        console.log(form)
        wx.request({
          url: HOST + 'v1/dictionary/getListByType/' + param,
          method: 'GET',
          success: function (res) {
            if (res.data.sysCode === 1) {
                let data = res.data.data
                let val = 0

                data.forEach((v, idx) => {
                    if (v.value == form[type]) {
                        val = idx
                    }
                })

                switch (type) {
                    case 'province':
                        this.setData({
                            provinces: res.data.data,
                            provincesIndex: val
                        })
                        this.getDictChain(form.province, 'city')
                        break
                    case 'city':
                        this.setData({
                            cities: res.data.data,
                            citiesIndex: val
                        })
                        this.getDictChain(form.city, 'area')
                        break
                    case 'area':
                        this.setData({
                            area: res.data.data,
                            areaIndex: val
                        })
                        break
                    default:
                        break
                }

            }
          }.bind(this)
        })
    },

    /**
     * 展示对话框
     * 
     * @param {String}  title      标题
     * @param {String}  content    内容
     * @param {Boolean} showCancel 是否显示取消按钮
     */
    showModal (title, content, showCancel, cb) {
        let self = this
        wx.showModal({
            title,
            content,
            showCancel,
            success (res) {
                cb && cb.apply(self, res)
            }
        })
    },

    /**
     * 保存地址
     */
    saveAddress () {
        let self = this
        let url, method
        let type = this.data.type

        if (!this.inspectAddress()) {
            return
        }

        let phone = parseInt(this.data.form.linkmanPhone)
        let regExp = /^1[0-9]{10}$/
        if (!regExp.test(phone)) {
            wx.showModal({
                title: '电话号码',
                content: '请输入正确的电话号码',
                showCancel: false,
                success (res) {
                    if (res.confirm) {
                        self.setData({
                            'form.linkmanPhone': ''
                        })
                    }
                }
            })
            return
        }

        wx.showToast({
            title: '正在保存',
            icon: 'loading',
            duration: 5000
        })

        wx.request({
            url: HOST + 'v1/userAddress',
            data: Object.assign({}, self.data.form, {userId: app.userId}),
            method: 'POST',
            success: function(res){
                if (res.data.sysCode === 1) {
                    wx.hideToast()
                    wx.showModal({
                        title: '保存成功',
                        content: '保存地址成功!',
                        showCancel: false,
                        success (res) {
                            if (res.confirm) {
                                wx.navigateBack({
                                    delta: 1,
                                })
                            }
                        }
                    })
                } else {
                    wx.hideToast()
                    wx.showToast({
                        title: '保存失败',
                        content: '保存地址失败，请重试！',
                        showCancel: false
                    })
                }
            }
        })
    },

    inspectAddress () {
        let pass = true

        for (let key in this.data.form) {
            if (!this.data.form[key] && key !== 'isDefault' && key !== 'code') {
                wx.showModal({
                    title: '添加地址出错！',
                    content: '请输入' + this.data.dict[key],
                    showCancel: false,
                    success (res) {
                    }
                })
                pass = false
                break
            }
        }

        return pass
    },

    /**
     * 修改地址时，获取地址
     */
    getAddress (id) {
        let self = this
        wx.request({
            url: HOST + 'v1/userAddress/getById/' + id,
            method: 'GET',
            success: function(res){
                if (res.data.sysCode === 1) {
                    let form = res.data.data
                    self.setData({
                        form
                    })
                    self.getDictChain(0, 'province')
                }
            }
        })
    },

    onLoad (options) {
        // 页面初始化 options为页面跳转所带来的参数
        this.setData({
            type: options.type,
            id: options.id,
            isInit: options.init === 1 ? true : false,
            isDefault: options.init === 1 ? true : false
        })

        this.getDict(0, 'province');
        if (options.type !== 'add') {
            this.getAddress(options.id)
        }
    }
})